package de.fuberlin.inf.utils;

import java.text.SimpleDateFormat;
import javax.activity.InvalidActivityException;

/**
 * This class helps to time durations.
 * @author stefanr
 */
public class Timer {
	private long tsBefore;
	private long milliseconds;
	private boolean running;
	
	/**
	 * Starts the timer.
	 * @throws InvalidActivityException if the timer is already running
	 */
	public void start() throws InvalidActivityException {
		if (this.running)
			throw new InvalidActivityException("Timer is already running");
		this.tsBefore = System.currentTimeMillis();
		this.running = true;
	}
	
	/**
	 * Stops the timer.
	 * @return The length of time in milliseconds.
	 * @throws InvalidActivityException if the timer is not running.
	 */
	public long stop() throws InvalidActivityException {
		if (!this.running)
			throw new InvalidActivityException("Timer is not running");
		this.milliseconds = System.currentTimeMillis() - this.tsBefore;
		this.running = false;
		return this.milliseconds;
	}

	@Override
	public String toString() {
		return new SimpleDateFormat("mm:ss.SSS" ).format( this.milliseconds );
	}
}
